package com.lcc.forum.demos.web.controller;

import com.lcc.forum.demos.web.common.AppResult;
import com.lcc.forum.demos.web.common.ResultCode;
import com.lcc.forum.demos.web.config.AppConfig;
import com.lcc.forum.demos.web.model.Article;
import com.lcc.forum.demos.web.model.ArticleReply;
import com.lcc.forum.demos.web.model.User;
import com.lcc.forum.demos.web.services.IArticleReplyService;
import com.lcc.forum.demos.web.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/reply")
@Api(tags = "回复接口")
public class ArticleReplyController {
    @Resource
    private IArticleReplyService articleReplyService;
    @Resource
    private IArticleService articleService;
    @PostMapping("/create")
    @ApiOperation("回复帖子")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("主贴子的Id") @RequestParam("articleId") @NonNull Long articleId,
                            @ApiParam("回复内容") @RequestParam("content") @NonNull String content){
        //校验当前登录用户是否被禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验帖子是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验帖子是否封贴
        if(article.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //创建回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        //调用service--写入回复
        articleReplyService.create(articleReply);
        //操作成功，返回结果
        return AppResult.success();
    }
    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam("主贴Id") @RequestParam("articleId") @NonNull Long articleId){
        //校验参数有效性
        //校验对应的主贴是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //调用service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        //返回结果
        return AppResult.success(articleReplies);
    }
}
